package com.jblv.frame.common.utils.jwt;

import com.jblv.frame.common.utils.jwt.jackjson.JsonParser;
import com.jblv.frame.common.utils.jwt.jackjson.JsonParserFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;

import java.io.*;
import java.util.Map;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title JwtDecodeUtils
 * @projectName jblv-frame
 * @packageName com.jblv.common.utils.jwt
 * @description JwtDecodeUtils
 * @date Create at 2020/4/30 23:21
 * @since jdk1.8
 */
public class JwtDecodeUtils {
    private static JsonParser objectMapper = JsonParserFactory.create();
    private static String verifierKey = null;
    private static SignatureVerifier verifier = null;

    public JwtDecodeUtils() {
    }

    public static Map<String, Object> decode(String token) throws Exception {
        try {
            Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
            String content = jwt.getClaims();
            Map<String, Object> map = objectMapper.parseMap(content);
            return map;
        } catch (Exception var4) {
            throw new Exception("Cannot convert access token to JSON", var4);
        }
    }

    public static String inputStream2String(InputStream in) {
        InputStreamReader reader = null;

        try {
            reader = new InputStreamReader(in, "UTF-8");
        } catch (UnsupportedEncodingException var6) {
            var6.printStackTrace();
        }

        BufferedReader br = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String line = "";

        try {
            while((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException var7) {
            var7.printStackTrace();
        }

        return sb.toString();
    }

    static {
        ClassPathResource resource = new ClassPathResource("public.txt");

        try {
            verifierKey = inputStream2String(resource.getInputStream());
        } catch (IOException var2) {
            throw new RuntimeException(var2);
        }

        verifier = new RsaVerifier(verifierKey);
    }
}
